package MINA.minaServ;


import MINA.minaServ.MyEncode.MyfilterFactory;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.keepalive.KeepAliveFilter;
import org.apache.mina.filter.keepalive.KeepAliveMessageFactory;
import org.apache.mina.filter.keepalive.KeepAliveRequestTimeoutHandler;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * Created by kz on 2017/5/1.
 */
public class minaserver {
    private static final int Port = 8888;

    private static final int PORT = 9123;
    /**
     * 30秒后超时
     */
    private static final int IDELTIMEOUT = 30;
    /**
     * 15秒发送一次心跳包
     */
    private static final int HEARTBEATRATE = 15;
    /**
     * 心跳包内容
     */
//    private static final String HEARTBEATREQUEST = "0x11";
//    private static final String HEARTBEATRESPONSE = "0x12";

    public static final byte HEARTBEATREQUEST = 11;
    public static final byte HEARTBEATRESPONSE = 12;

    private static final Logger LOG = LoggerFactory.getLogger(minaserver.class);

    private static class Timeouthandler implements KeepAliveRequestTimeoutHandler {

        @Override
        public void keepAliveRequestTimedOut(KeepAliveFilter keepAliveFilter, IoSession ioSession) throws Exception {
            ioSession.closeNow();
            System.out.println("TIME OUT 断线");
        }
    }

    private static class KeepAliveMessageFactoryImpl implements
            KeepAliveMessageFactory {

        @Override
        public boolean isRequest(IoSession session, Object message) {
            LOG.info("请求心跳包信息: " + message);
            if (message.equals(HEARTBEATREQUEST))
                return true;
            return false;
        }

        @Override
        public boolean isResponse(IoSession session, Object message) {
            LOG.info("响应心跳包信息: " + message);
            if (message.equals(HEARTBEATRESPONSE))
                return true;
            return false;
        }

        @Override
        public Object getRequest(IoSession session) {
            LOG.info("请求预设信息: " + HEARTBEATREQUEST);
            /** 返回预设语句 */
            return HEARTBEATREQUEST;
        }

        @Override
        public Object getResponse(IoSession session, Object request) {
            LOG.info("响应预设信息: " + HEARTBEATRESPONSE);
            /** 返回预设语句 */
            return HEARTBEATRESPONSE;
//          return null;
        }

    }


    public static void main(String[] args) {
        IoAcceptor ioAcceptor = new NioSocketAcceptor();
        System.out.println("服务器开启");

        ioAcceptor.getFilterChain().addLast("logger", new LoggingFilter());     //记录用LOGGER,不参与编码

//        ioAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));      //来回通讯用回车符表示结束


      /*  KeepAliveMessageFactory heartBeatFactory = new KeepAliveMessageFactoryImpl();       //心跳包的FILTER工厂
        KeepAliveFilter keepAliveFilter = new KeepAliveFilter(heartBeatFactory);            //filter
        keepAliveFilter.setRequestTimeout(1000);//10秒心跳

        keepAliveFilter.setRequestTimeoutHandler( new Timeouthandler());
        ioAcceptor.getFilterChain().addLast("keepAlive",keepAliveFilter);*/



        ioAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MyfilterFactory()));       //自己的解码编码器

        ioAcceptor.setHandler(new HelloWorldHandler());                                      //消息处理器

        ioAcceptor.getSessionConfig().setReadBufferSize(8192);                               //基础通讯设置
        ioAcceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
        try {
            ioAcceptor.bind(new InetSocketAddress(Port));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("端口绑定失败");
            e.printStackTrace();
        }
    }


}
